﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient; 
using System.Collections;
using System.Reflection;
using System.Runtime.Serialization;
using System.Windows.Forms;

using YT.Controls;
using YT.Commons; 


using System.IO;


namespace YT.Commons
{
    public class BaseFunctions
    {
        public BaseFunctions()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region From DataFunction
        public static bool NeedValidGridCell(Control CurrentControl, string strGridViewName)
        {
            if (CurrentControl != null)
            {
                if (CurrentControl.Name == strGridViewName)
                {
                    return true;
                }
                else
                {
                    if (CurrentControl.Parent != null)
                    {
                        return NeedValidGridCell(CurrentControl.Parent, strGridViewName);
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }
        }
        public static bool TrigerKeyEventByControl(Control CurrentControl, string strGridViewName)
        {
            if (CurrentControl == null) return false;
            if (CurrentControl.Name == strGridViewName)
            {
                return true;
            }
            else
            {
                if (CurrentControl.Parent != null)
                {
                    return NeedValidGridCell(CurrentControl.Parent, strGridViewName);
                }
                else
                {
                    return false;
                }
            }
        }
        #region GetWhereCondition
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="Value"></param>
        /// <param name="dataType"></param>
        /// <param name="rangeType"></param>
        /// <returns></returns>
        public static string GetWhereCondition(string FieldName, string Value, DataType dataType, RangeType rangeType)
        {
            StringBuilder sqlBuilder = new StringBuilder();

            if (Value != null && Value != "")
            {
                sqlBuilder.Append(" AND ")
                    .Append(FieldName)
                    .Append(ConvertRangeType(rangeType));

                if (dataType == DataType.String || dataType == DataType.DateTime)
                    if (rangeType == RangeType.Like)
                        sqlBuilder.Append("'%")
                            .Append(Value)
                            .Append("%'");
                    else
                        sqlBuilder.Append("'")
                            .Append(Value)
                            .Append("'");

                else
                {
                    if (Value == "0")
                        sqlBuilder.Remove(0, sqlBuilder.Length);
                    else
                        sqlBuilder.Append(Value);
                }
            }

            return sqlBuilder.ToString();
        }

        public static string GetWhereCondition(string FieldName, string Value, DataType dataType)
        {
            return GetWhereCondition(FieldName, Value, dataType, RangeType.Equal);
        }

        public static string GetWhereCondition(string FieldName, string Value)
        {
            return GetWhereCondition(FieldName, Value, DataType.String, RangeType.Equal);
        }
        private static string ConvertRangeType(RangeType rangeType)
        {
            string ret = "";
            switch (rangeType)
            {
                case RangeType.Big:
                    ret = ">";
                    break;
                case RangeType.BigEqual:
                    ret = ">=";
                    break;

                case RangeType.Equal:
                    ret = "=";
                    break;
                case RangeType.Like:
                    ret = " like ";
                    break;
                case RangeType.SamllEqual:
                    ret = "<=";
                    break;
                case RangeType.Small:
                    ret = "<";
                    break;

            };

            return ret;
        }

        #endregion

        #region getFieldString : get fields string from SQL
        /// <summary>
        /// get fields string from SQL
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static string GetFieldsStringFromSQL(string strSql)
        {

            int i, j;
            i = strSql.ToUpper().IndexOf("SELECT", 0) + "SELECT".Length;
            j = strSql.ToUpper().IndexOf(" FROM ", 0);
            if (i >= 0 && j >= 0)
                return strSql.Substring(i, j - "SELECT".Length);
            else
                return "";


        }
        #endregion

        #region FromSqlToArray : get array from SQL
        public static string[] FromSqlToArray(string strSql)
        {
            string strFieldPart = "";
            //            int i = 0;
            strFieldPart = GetFieldsStringFromSQL(strSql);
            strFieldPart.Replace('\n', ' ');
            strFieldPart.Replace('\r', ' ');
            return strFieldPart.Split(',');

        }
        #endregion

        #region Get field postion index from SQL
        /// <summary>
        /// Get field postion index from SQL
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="strFieldName"></param>
        /// <returns></returns>

        public static int GetFieldIndexFromSql(string strSql, string strFieldName)
        {
            string strTmpFieldName = "";
            string[] FieldArray = FromSqlToArray(strSql);
            for (int i = 0; i < FieldArray.Length; i++)
            {
                strTmpFieldName = FieldArray[i].Trim();
                if (strTmpFieldName.Substring(0, 1) == "[") strTmpFieldName = strTmpFieldName.Substring(1);
                if (strTmpFieldName.Substring(strTmpFieldName.Length - 1, 1) == "]") strTmpFieldName = strTmpFieldName.Substring(0, strTmpFieldName.Length - 1);
                if (strTmpFieldName.IndexOf(' ') > 0) strTmpFieldName = strTmpFieldName.Substring(0, strTmpFieldName.IndexOf(' ')).Trim();
                if (strTmpFieldName.ToUpper() == strFieldName.ToUpper())
                {
                    return i;
                }
            }
            return -1;
        }
        #endregion

        #region ConvertSqlDataTypeToWPDataType
        public static DataType ConvertSqlDataType(string strDataTypeName)
        {
            DataType dataType = DataType.String;

            if (strDataTypeName == "Boolean")
            {
                dataType = DataType.Bool;
            }
            else if (strDataTypeName == "Int16" || strDataTypeName == "Int32" || strDataTypeName == "Int64" || strDataTypeName == "UInt16" || strDataTypeName == "UInt32" || strDataTypeName == "UInt64")
            {
                dataType = DataType.Integer;
            }
            else if (strDataTypeName == "Decimal" || strDataTypeName == "Single" || strDataTypeName == "Double")
            {
                dataType = DataType.Numeric;
            }
            else if (strDataTypeName == "DateTime")
            {
                dataType = DataType.DateTime;
            }
            else if (strDataTypeName == "String" || strDataTypeName == "Char" || strDataTypeName == "Varchar")
            {
                dataType = DataType.String;
            }
            else if (strDataTypeName == "Byte[]" || strDataTypeName == "Byte" || strDataTypeName == "TimeSpan" || strDataTypeName == "SByte")
            {
                dataType = DataType.Byte;
            }

            return dataType;
        }
        #endregion

        #region ProgsArrayToString: Convert progress Array field to a string
        /// <summary>
        /// Convert progress Array field to a string
        /// </summary>
        /// <param name="strFieldMain">like "budget"</param>
        /// <param name="strStartNumber">like "01"</param>
        /// <param name="strEndNumber">like "24"</param>
        /// <param name="strDelimiter">like ", " or " + " etc.</param>
        /// <param name="bWithLastDelimiter">like "budget01, budget02, budget03......budget24</param>
        /// <returns></returns>
        public static string ProgsArrayToString(string strFieldMain, int intStNumber,
            int intEnNumber, string strDelimiter, bool bWithLastDelimiter)
        {
            string strAggregate = "";
            int intDelimiterPos = 0;

            if (intStNumber > intEnNumber)
            {
                throw new Exception("End number must be larger than start number!");
            }

            for (int i = intStNumber; i <= intEnNumber; i++)
            {
                strAggregate += strFieldMain + i.ToString().PadLeft(2, '0') + strDelimiter;
            }

            if (!bWithLastDelimiter)
            {
                intDelimiterPos = strAggregate.LastIndexOf(strDelimiter, strAggregate.Length);
                strAggregate = strAggregate.Substring(0, intDelimiterPos);
            }

            return strAggregate;
        }
        #endregion

        #region FormatField
        public static string FormatField(string strField_char, string strFormatStyle)
        {
            int iLength;
            if (strFormatStyle == null || strFormatStyle.Length < 1)
            {
                return strField_char;
            }
            switch (strFormatStyle.Substring(0, 1).ToUpper())
            {
                case "B":
                    iLength = Convert.ToInt32(strFormatStyle.Substring(1));
                    return FormatWithBlank(strField_char, iLength);
                case "N":
                    return FormatNumeric(strField_char.Trim(), strFormatStyle.Trim());
                case "L":
                    return strField_char.ToLower();
                case "U":
                    return strField_char.ToUpper();
                case "Z":
                    iLength = Convert.ToInt32(strFormatStyle.Substring(1));
                    return FormatWithZero(strField_char, iLength);

                default:
                    return strField_char;
            }

        }
        #endregion

        #region FormatNumeric:Format numeric according format style ,like as "NN","N.S","NN.N" etc
        public static string FormatNumeric(object dblData, string strFormatStyle)
        {
            if (dblData == null) dblData = "";
            return FormatNumeric(dblData.ToString(), strFormatStyle);
        }
        public static string FormatNumeric(double dblData, string strFormatStyle)
        {
            return FormatNumeric(dblData.ToString(), strFormatStyle);
        }
        public static string FormatNumeric(string strData, string strFormatStyle)
        {
            int intDigitPos = 0;
            bool blnTrimEndZeroChar = false;
            string strValue1 = "", strValue2 = "";

            if (strFormatStyle.ToUpper().Trim() == "N.?")
            {
                blnTrimEndZeroChar = true;
                strFormatStyle = "N.N";
            }

            if (strFormatStyle.ToUpper().Trim() == "NS.?")
            {
                blnTrimEndZeroChar = true;
                strFormatStyle = "NS.N";
            }

            strData = strData.Replace(",", "").Trim();

            //Format the strData to NumerricType
            if (!BaseFunctions.IsNumeric(strData))
            {
                strData = "0";
            }
            else
            {
                if (strData.Substring(0, 1) == ".")
                    strData = "0" + strData;
                if (strData.Substring(strData.Length - 1, 1) == ".")
                    strData = strData.Substring(0, strData.Length - 1);
            }
            switch (strFormatStyle.ToUpper())
            {
                case "NN"://no format , remove "," in strField_Char  and remove left "0"
                    strData = strData.Replace(",", "");
                    while (strData.Substring(0, 1) == "0" && strData.Length > 1 && strData.Substring(1, 1) != ".")
                    {
                        strData = strData.Substring(1, strData.Length - 1);
                    }
                    return (strData);
                case "N.N"://no format , remove "," in strField_Char  and remove left "0"
                    strData = strData.Replace(",", "");
                    while (strData.Substring(0, 1) == "0" && strData.Length > 1 && strData.Substring(1, 1) != ".")
                    {
                        strData = strData.Substring(1, strData.Length - 1);
                    }
                    if (blnTrimEndZeroChar)
                    {
                        while (strData.IndexOf(".") >= 0 && strData.Length > 0 && strData.Substring(strData.Length - 1, 1) == "0")
                        {
                            strData = strData.Substring(0, strData.Length - 1);
                        }
                        if (strData.Length > 0 && strData.Substring(strData.Length - 1, 1) == ".") strData = strData.Substring(0, strData.Length - 1);
                    }
                    if (strData.Trim() == "") strData = "0";
                    return (strData);
                case "NS.N"://'number do not format ,but need add number separator ","
                    strData = strData.Replace(",", "");

                    intDigitPos = strData.IndexOf(".", 0);//get the position of radix point
                    if (intDigitPos > 0)
                    {
                        strValue1 = FormatSeparatorNumeric(strData.Substring(0, intDigitPos));
                        strValue2 = strData.Substring(intDigitPos + 1, strData.Length - intDigitPos - 1);
                        strData = strValue1 + "." + strValue2;
                    }
                    else
                        strData = FormatSeparatorNumeric(strData);
                    if (blnTrimEndZeroChar)
                    {
                        while (strData.IndexOf(".") >= 0 && strData.Length > 0 && strData.Substring(strData.Length - 1, 1) == "0")
                        {
                            strData = strData.Substring(0, strData.Length - 1);
                        }
                        if (strData.Length > 0 && strData.Substring(strData.Length - 1, 1) == ".") strData = strData.Substring(0, strData.Length - 1);
                    }
                    if (strData.Trim() == "") strData = "0";
                    return (strData);
                case "NS"://'number do not format ,but need add number separator ","
                    strData = strData.Replace(",", "");

                    intDigitPos = strData.IndexOf(".", 0);//get the position of radix point
                    if (intDigitPos > 0)
                    {
                        strValue1 = FormatSeparatorNumeric(strData.Substring(0, intDigitPos));
                        strValue2 = strData.Substring(intDigitPos + 1, strData.Length - intDigitPos - 1);
                        strData = strValue1 + "." + strValue2;
                    }
                    else
                        strData = FormatSeparatorNumeric(strData);
                    return (strData);
                default:
                    if (strFormatStyle.IndexOf(".") >= 0 && BaseFunctions.IsNumeric(strFormatStyle.Substring(strFormatStyle.IndexOf(".") + 1)))
                    {

                        strData = Round(strData, Int32.Parse(strFormatStyle.Substring(strFormatStyle.IndexOf(".") + 1)));

                        //strData = decimal.Round(decimal.Parse(strData, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowLeadingSign), Int32.Parse(strFormatStyle.Substring(strFormatStyle.IndexOf(".") + 1)), MidpointRounding.ToEven  ).ToString();

                    }
                    break;
            }

            strFormatStyle = strFormatStyle.Substring(1, strFormatStyle.Length - 1).ToUpper();

            string strChar = string.Empty;
            if (strFormatStyle != string.Empty)
                strChar = strFormatStyle.Substring(0, 1);

            bool bSp = false;

            if (strChar == "S")
            {
                bSp = true;
                strFormatStyle = strFormatStyle.Substring(1, strFormatStyle.Length - 1);
            }
            else if ((strChar == ".") || (strChar == "") || (Char.IsNumber(strChar, 0)))
            {
                bSp = false;
            }
            else if (((char.Parse(strChar)) >= 'A' && (char.Parse(strChar)) <= 'R') || ((char.Parse(strChar)) >= 'T' && (char.Parse(strChar)) <= 'Z'))
            {
                bSp = false;
                strFormatStyle = strFormatStyle.Substring(1, strFormatStyle.Length - 1);
            }
            else
            {
                return (strData);
            }

            int intWidth = 0;
            int intScaleWidth = 0;
            // string strAddChar = "";
            int intForLen = 0;

            intDigitPos = strFormatStyle.IndexOf(".");

            if (intDigitPos < 0) //"N" , "NS"
            {
                if (strFormatStyle == string.Empty)
                    intWidth = 0;
                else
                    intWidth = Int32.Parse(strFormatStyle);
                intScaleWidth = 0;
            }
            else if (intDigitPos == 0) //"N.2" ,"NS.2"
            {
                intWidth = 0;
                intScaleWidth = Int32.Parse(strFormatStyle.Substring(1, strFormatStyle.Length - 1)); ;
            }
            else if (intDigitPos >= 1) //"NS10.2" , "NS10.2B" , "NS10.2Z"
            {
                intWidth = Int32.Parse(strFormatStyle.Substring(0, intDigitPos));
                intScaleWidth = Int32.Parse(strFormatStyle.Substring(intDigitPos + 1));
            }


            //Add scale
            if (intScaleWidth > 0)
            {
                intDigitPos = strData.IndexOf(".");
                if (intDigitPos >= 0)
                {
                    strValue2 = strData.Substring(intDigitPos + 1, strData.Length - intDigitPos - 1);
                }
                else
                {
                    strData = strData + ".";
                    strValue2 = "";
                }
                intForLen = intScaleWidth - strValue2.Length;
                if (intForLen > 0)
                {
                    for (int i = 0; i < intForLen; i++)
                    {
                        strData += "0";
                    }
                }

            }

            //Add spearater
            if (bSp)
            {
                strData = strData.Replace(",", "");
                intDigitPos = strData.IndexOf(".");
                if (intDigitPos >= 0)
                {
                    strValue1 = FormatSeparatorNumeric(strData.Substring(0, intDigitPos));
                    strValue2 = strData.Substring(intDigitPos + 1, strData.Length - intDigitPos - 1);
                    strData = strValue1 + "." + strValue2;

                }
                else
                {
                    strData = FormatSeparatorNumeric(strData);
                }
            }

            return strData;

        }

        private static string FormatSeparatorNumeric(string strData)
        {
            string StrTemp = "", strSign = "";
            int iIndex = 0;

            if (strData.Length > 0 && strData.Substring(0, 1) == "-")
            {
                strSign = "-";
                strData = strData.Substring(1);

            }
            int intLen = strData.Length;
            for (int i = intLen - 1; i >= 0; i--)
            {
                iIndex++;
                StrTemp = strData.Substring(i, 1) + StrTemp;
                if (iIndex % 3 == 0)
                    StrTemp = "," + StrTemp;
            }

            if (StrTemp != "" && StrTemp[0] == ',')
            {
                StrTemp = StrTemp.Substring(1, StrTemp.Length - 1);
            }
            return (strSign + StrTemp);
        }

        private static int GetIntFromStr(string strData)
        {
            string strTemp = "";
            int intNum = 0;
            int intLen = strData.Length;
            for (int i = 0; i < intLen; i++)
            {
                if (Char.IsNumber(strData[i]))
                {
                    strTemp += strData.Substring(i, 1);
                }
            }

            if (strTemp != "")
            {
                intNum = int.Parse(strTemp);
            }
            return (intNum);
        }

        public static string Round(string strdata, int iDecimal)
        {
            strdata = strdata.Replace(",", "").Trim();
            int iPointLocate = strdata.IndexOf('.');
            bool bIsNegative = (strdata.IndexOf('-') != -1);
            if (iPointLocate <= 0) return strdata;

            int iDecimalScale = strdata.Length - iPointLocate - 1;
            if (iDecimalScale <= iDecimal) return strdata;
            int iDigit = int.Parse(strdata.Substring(iPointLocate + iDecimal + 1, 1));
            if (iDigit >= 5)
            {
                if (bIsNegative)
                    strdata = Convert.ToString(double.Parse(strdata.Substring(0, iPointLocate + iDecimal + 1)) - 1 / Math.Pow(10, iDecimal));
                else
                    strdata = Convert.ToString(double.Parse(strdata.Substring(0, iPointLocate + iDecimal + 1)) + 1 / Math.Pow(10, iDecimal));
            }
            else
            {
                strdata = Convert.ToString(double.Parse(strdata.Substring(0, iPointLocate + iDecimal + 1)));
            }
            return strdata;
        }

        #endregion

        #region Deal The Special Chars occured when operate the database
        /// <summary>
        /// Created at 4/25/2005
        /// function : Deal The Special Chars occured when operate the database
        /// Remark : Has overload 3 times for string , NameValueCollection , DataSet
        /// </summary>
        /// <param name="dsOrigin"></param>
        /// <returns></returns>
        public static void SpecialCharDeal(DataSet dsOrigin)
        {
            for (int i = 0; i < dsOrigin.Tables.Count; i++)
            {
                SpecialCharDeal(dsOrigin.Tables[i]);
            }
        }

        public static void SpecialCharDeal(DataSet dsOrigin, string strTableName)
        {
            SpecialCharDeal(dsOrigin.Tables[strTableName]);
        }

        public static void SpecialCharDeal(DataTable dtOrigin)
        {

            for (int j = 0; j < dtOrigin.Rows.Count; j++)
            {
                for (int m = 0; m < dtOrigin.Columns.Count; m++)
                {
                    if (dtOrigin.Rows[j][m] != DBNull.Value && dtOrigin.Rows[j][m].ToString().Length != 0 && dtOrigin.Columns[m].DataType.Name == "String")
                    {
                        dtOrigin.Rows[j][m] = SpecialCharDeal(dtOrigin.Rows[j][m].ToString());
                    }
                }
            }

            dtOrigin.AcceptChanges();
        }


        public static string SpecialCharDeal(string strOrigin)
        {

            if (strOrigin == null) return "";
            if (strOrigin.IndexOf("'", 0) >= 0)
            {
                strOrigin = strOrigin.Replace("'", "''");
            }

            return strOrigin;
        }

       
        #endregion

        #region CnFieldValueFromRs

        public static bool IsNumericType(string strFiledType)
        {
            strFiledType = strFiledType.ToLower().Trim();
            return strFiledType == "Int32".ToLower() || strFiledType == "Decimal".ToLower();
        }

        public static string CnFieldValueFromRs(object objValue, string strFiledType)
        {
            if (strFiledType == "String" || strFiledType == "DateTime")
            {
                if (strFiledType == "DateTime" && (objValue == DBNull.Value))
                    return "";
                else
                {
                    if (strFiledType == "DateTime")
                    {
                        return FormatDate(objValue.ToString());
                    }
                    else
                    {
                        return objValue.ToString();
                    }
                }
            }
            else if (strFiledType == "Int32")
            {
                return CvtFunc.ToInt(objValue).ToString();
            }
            else if (strFiledType == "Decimal")
            {
                return CvtFunc.ToDouble(objValue).ToString();
            }
            else
            {
                return objValue.ToString();
            }
        }
        #endregion CnFieldValueFromRs

        #region GetFieldTypeFromRs
        public static string GetFieldTypeFromRs(string strFiledType)
        {
            string strGetFieldTypeFromRs;
            switch (strFiledType)
            {
                case "Decimal":
                case "Double":
                case "Int16":
                case "Int32":
                case "Int64":
                case "Single":
                case "UInt16":
                case "UInt32":
                case "UInt64":
                    strGetFieldTypeFromRs = "num";                 //numberic type
                    break;
                case "Boolean":
                    strGetFieldTypeFromRs = "bln";                 //logic type
                    break;
                case "Char":
                case "String":
                    strGetFieldTypeFromRs = "str";                 //char type
                    break;
                case "DateTime":
                case "TimeSpan":
                    strGetFieldTypeFromRs = "dat";                 //date type
                    break;
                case "Byte":
                case "SByte":
                    strGetFieldTypeFromRs = "bin";
                    break;
                default:
                    strGetFieldTypeFromRs = "Err";
                    break;
            }
            return strGetFieldTypeFromRs;
        }
        #endregion GetFieldTypeFromRs

        #region Generate a Update or Indert Sql by tablename,fields and data for DataAccess
        public static string GenerateSqlForDataAccess(string strFieldName, string strTableName, DataRow dr, FormStatus formStatus)
        {
            return GenerateSqlForDataAccess(strFieldName, strTableName, dr, formStatus, "RecID", true);
        }
        public static string GenerateSqlForDataAccess(string strFieldName, string strTableName, DataRow dr, FormStatus formStatus, string strKeyFieldName, bool blnNeedGetTimestamp)
        {
            StringBuilder sbSql = new StringBuilder();
            StringBuilder sbFieldNameValue = new StringBuilder();
            StringBuilder sbFieldNames = new StringBuilder();
            string[] strFieldNames;
            string strDateType = "";
            if (dr != null)
            {
                DataTable dt = dr.Table;
                if (strFieldName.IndexOf("\r") >= 0)
                    strFieldName = strFieldName.Replace("\r", "");
                if (strFieldName.IndexOf("\n") >= 0)
                    strFieldName = strFieldName.Replace("\n", "");
                if (strFieldName.IndexOf("\t") >= 0)
                    strFieldName = strFieldName.Replace("\t", "");

                strFieldNames = strFieldName.Split(',');
                #region add mode
                if (formStatus == FormStatus.AddNew)
                {
                    for (int i = 0; i < strFieldNames.Length; i++)
                    {

                        strFieldName = strFieldNames[i].Trim();
                        sbFieldNames.Append(strFieldName).Append(",");
                        strDateType = dt.Columns[strFieldName].DataType.Name;

                        if (strDateType == "String" || strDateType == "DateTime")
                        {
                            if (strDateType == "DateTime" && (dr[strFieldName] == DBNull.Value))
                                sbFieldNameValue.Append("null,");
                            else
                            {
                                if (strDateType == "DateTime")
                                {
                                    sbFieldNameValue.Append("'")
                                        .Append(FormatDate(dr[strFieldName].ToString()))
                                        .Append("'").Append(",");
                                }
                                else
                                {
                                    sbFieldNameValue.Append("'")
                                        .Append(dr[strFieldName].ToString().Replace("'", "''"))
                                        .Append("'").Append(",");
                                }
                            }
                        }
                        else if (strDateType == "Int32")
                        {
                            sbFieldNameValue.Append(CvtFunc.ToInt(dr[strFieldName]).ToString())
                                .Append(",");
                        }
                        else if (strDateType == "Decimal")
                        {
                            sbFieldNameValue.Append(CvtFunc.ToDouble(dr[strFieldName]).ToString())
                                .Append(",");
                        }
                        else if (strDateType == "Boolean")
                        {
                            sbFieldNameValue.Append(CvtFunc.ToBoolean(dr[strFieldName]).ToString())
                                .Append(",");
                        }
                        else
                        {
                            sbFieldNameValue.Append(dr[strFieldName].ToString())
                                .Append(",");
                        }
                    }
                    sbSql.Append("INSERT INTO ")
                        .Append(strTableName)
                        .Append(" (")
                        .Append(sbFieldNames.ToString().TrimEnd(','))
                        .Append(") VALUES (")
                        .Append(sbFieldNameValue.ToString().TrimEnd(','))
                        .Append(")")
                        .Append(";Select @@identity");

                }
                #endregion
                #region update mode
                else if (formStatus == FormStatus.Update)
                {
                    sbSql.Append("UPDATE ");
                    sbSql.Append(strTableName);
                    sbSql.Append(" SET ");
                    for (int i = 0; i < strFieldNames.Length; i++)
                    {
                        strFieldName = strFieldNames[i].Trim();
                        strDateType = dt.Columns[strFieldName].DataType.Name;
                        if (strDateType == "String" || strDateType == "DateTime")
                        {
                            sbSql.Append(strFieldName);

                            if (strDateType == "DateTime" && (dr[strFieldName] == DBNull.Value))
                                sbSql.Append("=null,");
                            else
                                sbSql.Append("='")
                                    .Append(dr[strFieldName].ToString().Replace("'", "''"))
                                    .Append("',");
                        }
                        else if (strDateType == "Int32")
                        {
                            sbSql.Append(strFieldName)
                                    .Append("=")
                                    .Append(CvtFunc.ToInt(dr[strFieldName]).ToString())
                                    .Append(",");
                        }
                        else if (strDateType == "Decimal")
                        {
                            sbSql.Append(strFieldName)
                                .Append("=")
                                .Append(CvtFunc.ToDouble(dr[strFieldName]).ToString())
                                .Append(",");

                        }
                        else if (strDateType == "Boolean")
                        {
                            sbSql.Append(strFieldName)
                                .Append("=")
                                    .Append(CvtFunc.ToBoolean(dr[strFieldName]).ToString())
                                    .Append(",");
                        }
                        else
                        {
                            sbSql.Append(strFieldName)
                                .Append("=")
                                .Append(dr[strFieldName].ToString())
                                .Append(",");
                        }

                    }
                    #region join key condition
                    string[] arrKeyField = strKeyFieldName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    StringBuilder sbKey = new StringBuilder();
                    foreach (string f in arrKeyField)
                    {
                        strDateType = dt.Columns[f].DataType.Name;
                        if (strDateType == "String" || strDateType == "DateTime")
                        {
                            sbKey.Append(f);
                            if (strDateType == "DateTime" && (dr[f] == DBNull.Value))
                                sbKey.Append("=null");
                            else
                                sbKey.Append("='")
                                    .Append(dr[f].ToString().Replace("'", "''"))
                                   .Append("'");
                        }
                        else if (strDateType == "Int32")
                        {
                            sbKey.Append(f)
                                    .Append("=")
                                    .Append(CvtFunc.ToInt(dr[f]).ToString());
                        }
                        else if (strDateType == "Decimal")
                        {
                            sbKey.Append(f)
                                .Append("=")
                                .Append(CvtFunc.ToDouble(dr[f]).ToString());

                        }
                        else
                        {
                            sbKey.Append(f)
                                .Append("=")
                                .Append(dr[f].ToString());
                        }
                        sbKey.Append(" and ");
                    }
                    sbKey.Remove(sbKey.Length - 5, 5);
                    sbKey = sbKey.Replace("False", "0").Replace("True", "1");
                    #endregion
                    sbSql.Remove(sbSql.Length - 1, 1)
                            .Append(" where " + sbKey.ToString());
                    if (blnNeedGetTimestamp)
                    {
                        sbSql.Append(";SELECT RecStamp FROM ")
                       .Append(strTableName)
                       .Append(" WHERE " + sbKey.ToString());
                    }

                }
                #endregion
                sbSql = sbSql.Replace("False", "0").Replace("True", "1");
            }
            return sbSql.ToString();
        }
        #endregion

      

        #region GetSystemModuleByMenuId
        public static SystemModules GetSystemModuleByMenuId(string strMenuId)
        {
            SystemModules systemModules = SystemModules.MeniereDisease;

            if (strMenuId.Length >= 3)
            {
                strMenuId = strMenuId.Substring(0, 3);

                if (strMenuId == "100")
                    systemModules = SystemModules.MeniereDisease;
                else if (strMenuId == "200")
                    systemModules = SystemModules.SUDDENDEAFNESS;                
                else
                    systemModules = SystemModules.Others ;
            }
            else
            {
                systemModules = SystemModules.Others;
            }

            return systemModules;
        }
        #endregion

        #region CompareDataRowsIsSame :Both DataRows must be same structrue
        /// <summary>
        /// Both DataRows must be same structrue
        /// </summary>
        /// <param name="drOne"></param>
        /// <param name="drTwo"></param>
        /// <returns></returns>
        public static bool CompareDataRowsIsSame(DataRow drOne, DataRow drTwo)
        {
            bool bSame = true;

            for (int i = 0; i < drOne.ItemArray.Length; i++)
            {
                if (drOne[i].ToString() != drTwo[i].ToString())
                {
                    System.Diagnostics.Debug.WriteLine("|" + drOne[i].ToString() + "|" + drTwo[i].ToString() + "|");
                    bSame = false;
                    break;
                }
            }

            return bSame;
        }
        #endregion

        #region Analyze sql

        #region Get sqlpart according to intSqlPart
        /// <summary>
        /// Get sqlpart according to intSqlPart
        /// </summary>
        /// <param name="strSQl">sql statement</param>
        /// <param name="sqlOption">sql option</param>
        /// SqlOption.SqlPartTablename  0
        /// SqlOption.SqlPartMain       1
        /// SqlOption.SqlPartWhere      2
        /// SqlOption.SqlPartOrderBy    3
        /// SqlOption.SqlPartInner      4
        /// SqlOption.SqlPartAll        5
        /// <returns>sqlpart according to intSqlPart</returns>
        public static string GetSqlParts(string strSQl, SqlOption sqlOption)
        {
            string strResult = String.Empty;

            int iStart = 0;
            int iEnd = 0;
            int iFieldCount = 0;
            string strMySQl = String.Empty;
            string strChar = String.Empty;

            int iSelectStart = 0;
            int iTableNameStart = 0;
            int iWhereStart = 0;
            int iOrderbyStart = 0;
            int iInnerStart = 0;
            int iLeftJoinStart = 0;
            int i = 0;

            string strTableName = String.Empty;
            string strField = String.Empty;
            string strMain = String.Empty;
            string strWhere = String.Empty;
            string strOrderby = String.Empty;
            string strInner = String.Empty;
            string strLeftJoin = String.Empty;
            //strSQl = strSQl.ToUpper();

            if (strSQl.Length <= 32766 && strSQl != null && strSQl.Trim().Length != 0)
            {
                strMySQl = strSQl.Trim();
                strMySQl = strMySQl.Replace("\n", " ").Replace("\t", " ").Replace("\r", " ");

                //calculate key word start position
                iSelectStart = GetSqlKeywordPos(strMySQl, "Select".ToUpper());
                iTableNameStart = GetSqlKeywordPos(strMySQl, "From".ToUpper());
                iWhereStart = GetSqlKeywordPos(strMySQl, "Where".ToUpper());
                iOrderbyStart = GetSqlKeywordPos(strMySQl, "Order by".ToUpper());
                iInnerStart = GetSqlKeywordPos(strMySQl, "Inner join".ToUpper());
                iLeftJoinStart = GetSqlKeywordPos(strMySQl, "left join".ToUpper());


                //Get TableName
                if (sqlOption == SqlOption.SqlPartTableName)
                {
                    #region ***Get Table Name
                    if (iTableNameStart > -1)
                    {
                        iStart = iTableNameStart;
                        //
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 4)//Len("from")=4
                        {
                            strResult = strMySQl.Substring(iStart + 5, iEnd - iStart - 4 - 1);
                            strResult = strResult.TrimStart();
                            i = strResult.IndexOf(' ');
                            if (i > 1) strResult = strResult.Substring(0, i);
                        }
                        else
                        {
                            if (iSelectStart == 0 && iTableNameStart == 0 && iWhereStart == 0
                                && iOrderbyStart == 0 && iInnerStart == 0 && iLeftJoinStart == 0)
                            {
                                strResult = strMySQl;
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartInner)
                {
                    #region ***Get Inner Sql
                    if (iInnerStart > -1)
                    {
                        iStart = iInnerStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 10)
                        {
                            strResult = strMySQl.Substring(iStart + 11, iEnd - iStart - 10 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " inner join ");
                            }
                        }
                    }

                    if (iLeftJoinStart > -1)
                    {
                        iStart = iLeftJoinStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 9)
                        {
                            strResult = strMySQl.Substring(iStart + 10, iEnd - iStart - 9 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " left join ");
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartWhere)
                {
                    #region ***Get Where Sql
                    if (iWhereStart > -1)
                    {
                        iStart = iWhereStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 5)
                        {
                            strResult = strMySQl.Substring(iStart + 6, iEnd - iStart - 5 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = "(" + strResult + ")";
                                strResult = strResult.Insert(0, " where ");
                            }
                        }
                    }
                    #endregion
                }
                else if (sqlOption == SqlOption.SqlPartOrderBy)
                {
                    #region ***Get Orderby Sql
                    if (iOrderbyStart > -1)
                    {
                        iStart = iOrderbyStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 9)
                        {
                            strResult = strMySQl.Substring(iStart + 9, iEnd - iStart - 8 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " ORDER BY ");
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartMain)
                {
                    #region ***Get Main Sql
                    strTableName = GetSqlParts(strMySQl, SqlOption.SqlPartTableName);
                    if (strTableName.Length != 0)
                    {
                        if (iSelectStart > -1)
                        {
                            iStart = iSelectStart;
                            //GoSub GetEndPos
                            iEnd = strMySQl.Length;
                            if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                            if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                            if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                            if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                            if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                            //
                            if (iEnd - iStart > 6)
                            {
                                strField = strMySQl.Substring(iStart + 7, iEnd - iStart - 6 - 1).Trim();
                                //RemakeFields: rebuild every field
                                if (strField.StartsWith("*") == false && strField.StartsWith("all") == false)
                                {
                                    strChar = String.Empty;
                                    strField += ",";
                                    i = GetSqlKeywordPos(strField, ",");

                                    while (i > -1)
                                    {
                                        if (i == 0)
                                        {
                                            strField = strField.Remove(0, 1);
                                        }
                                        else
                                        {
                                            if (strField.Substring(0, i).Trim() != String.Empty)
                                            {
                                                if (GetSqlKeywordPos(strField.Substring(0, i).Trim(), "as") > 0)
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                }
                                                else if ((GetSqlKeywordPos(strField.Substring(0, i).Trim(), "distinct") > 0))
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                }
                                                else if (strField.Substring(0, i).Trim().StartsWith("[") == true && strField.Substring(0, i).Trim().EndsWith("]") == true)
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                }
                                                //else if(strField.IndexOf(".") > -1)
                                                //{
                                                //    strChar=strField.Replace(".","")+",";
                                                //}
                                                else if ((strField.Substring(0, i).Trim().IndexOf(".") > -1) && (strField.Substring(0, i).IndexOf(".") < strField.Substring(0, i).Trim().Length))
                                                {
                                                    //                                                    strChar += Left(Trim(Left(strField, i - 1)), InStr(1, Trim(Left(strField, i - 1)), "."));
                                                    //                                                    strChar += Right(Trim(Left(strField, i - 1)), Len(Trim(Left(strField, i - 1))) - InStr(1, Trim(Left(strField, i - 1)), ".")) + ",";

                                                    strChar += strField.Substring(0, i).Trim().Substring(0, strField.Substring(0, i).Trim().IndexOf("."));
                                                    strChar += strField.Substring(0, i).Trim().Substring(strField.Substring(0, i).Trim().Length - (strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")), strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")) + ",";
                                                }
                                                else
                                                {
                                                    strChar += "[" + strField.Substring(0, i).Trim() + "],";
                                                }
                                                iFieldCount++;

                                            }
                                            strField = strField.Substring(i + 1).Trim();

                                        }
                                        i = GetSqlKeywordPos(strField, ",");

                                    }
                                    if (strChar == String.Empty)
                                    {
                                        strField = String.Empty;
                                    }
                                    else
                                    {
                                        strField = strChar;
                                        while (strField.EndsWith("\t") || strField.EndsWith("\n") || strField.EndsWith(","))
                                        {
                                            strField = strField.Remove(strField.Length - 1, 1);
                                        }
                                    }

                                }
                                //

                                if (strField.Length != 0)
                                {
                                    strMain = "select " + strField + " from " + strTableName;
                                    strResult = strMain;
                                }
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartAll)
                {
                    #region ***Get All Sql
                    strMain = GetSqlParts(strMySQl, SqlOption.SqlPartMain);
                    if (strMain.Length != 0)
                    {
                        //
                        strInner = GetSqlParts(strMySQl, SqlOption.SqlPartInner);
                        strWhere = GetSqlParts(strMySQl, SqlOption.SqlPartWhere);
                        strOrderby = GetSqlParts(strMySQl, SqlOption.SqlPartOrderBy);
                        strResult = strMain + String.Format(" {0} {1} {2} ", strInner, strWhere, strOrderby);
                    }
                    #endregion ***
                }

            }

            return strResult;
        }

        public static string GetSqlParts(string strSQl, SqlOption sqlOption, ref string[] fieldArray)
        {
            string strResult = String.Empty;

            int iStart = 0;
            int iEnd = 0;
            int iFieldCount = 0;
            string strMySQl = String.Empty;
            string strChar = String.Empty;
            string strFieldArray = String.Empty;

            int iSelectStart = 0;
            int iTableNameStart = 0;
            int iWhereStart = 0;
            int iOrderbyStart = 0;
            int iInnerStart = 0;
            int iLeftJoinStart = 0;
            int i = 0;

            string strTableName = String.Empty;
            string strField = String.Empty;
            string strMain = String.Empty;
            string strWhere = String.Empty;
            string strOrderby = String.Empty;
            string strInner = String.Empty;
            string strLeftJoin = String.Empty;
            //strSQl = strSQl.ToUpper();

            if (strSQl.Length <= 32766 && strSQl != null && strSQl.Trim().Length != 0)
            {
                strMySQl = strSQl.Trim();
                strMySQl = strMySQl.Replace("\n", " ").Replace("\t", " ").Replace("\r", " ");

                //calculate key word start position
                iSelectStart = GetSqlKeywordPos(strMySQl, "Select".ToUpper());
                iTableNameStart = GetSqlKeywordPos(strMySQl, "From".ToUpper());
                iWhereStart = GetSqlKeywordPos(strMySQl, "Where".ToUpper());
                iOrderbyStart = GetSqlKeywordPos(strMySQl, "Order by".ToUpper());
                iInnerStart = GetSqlKeywordPos(strMySQl, "Inner join".ToUpper());
                iLeftJoinStart = GetSqlKeywordPos(strMySQl, "left join".ToUpper());


                //Get TableName
                if (sqlOption == SqlOption.SqlPartTableName)
                {
                    #region ***Get Table Name
                    if (iTableNameStart > -1)
                    {
                        iStart = iTableNameStart;
                        //
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 4)//Len("from")=4
                        {
                            strResult = strMySQl.Substring(iStart + 5, iEnd - iStart - 4 - 1);
                            strResult = strResult.TrimStart();
                            i = strResult.IndexOf(' ');
                            if (i > 1) strResult = strResult.Substring(0, i);
                        }
                        else
                        {
                            if (iSelectStart == 0 && iTableNameStart == 0 && iWhereStart == 0
                                && iOrderbyStart == 0 && iInnerStart == 0 && iLeftJoinStart == 0)
                            {
                                strResult = strMySQl;
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartInner)
                {
                    #region ***Get Inner Sql
                    if (iInnerStart > -1)
                    {
                        iStart = iInnerStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 10)
                        {
                            strResult = strMySQl.Substring(iStart + 11, iEnd - iStart - 10 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " inner join ");
                            }
                        }
                    }

                    if (iLeftJoinStart > -1)
                    {
                        iStart = iLeftJoinStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 9)
                        {
                            strResult = strMySQl.Substring(iStart + 10, iEnd - iStart - 9 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " left join ");
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartWhere)
                {
                    #region ***Get Where Sql
                    if (iWhereStart > -1)
                    {
                        iStart = iWhereStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 5)
                        {
                            strResult = strMySQl.Substring(iStart + 6, iEnd - iStart - 5 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " where ");
                            }
                        }
                    }
                    #endregion
                }
                else if (sqlOption == SqlOption.SqlPartOrderBy)
                {
                    #region ***Get Orderby Sql
                    if (iOrderbyStart > -1)
                    {
                        iStart = iOrderbyStart;
                        //GoSub GetEndPos
                        iEnd = strMySQl.Length;
                        if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                        if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                        if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                        if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                        if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                        //
                        if (iEnd - iStart > 9)
                        {
                            strResult = strMySQl.Substring(iStart + 9, iEnd - iStart - 8 - 1);
                            if (strResult.Length != 0)
                            {
                                strResult = strResult.Insert(0, " ORDER BY ");
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartMain)
                {
                    #region ***Get Main Sql
                    strTableName = GetSqlParts(strMySQl, SqlOption.SqlPartTableName);
                    if (strTableName.Length != 0)
                    {
                        if (iSelectStart > -1)
                        {
                            iStart = iSelectStart;
                            //GoSub GetEndPos
                            iEnd = strMySQl.Length;
                            if (iStart < iSelectStart && iEnd > iSelectStart) { iEnd = iSelectStart - 1; }
                            if (iStart < iTableNameStart && iEnd > iTableNameStart) { iEnd = iTableNameStart - 1; }
                            if (iStart < iInnerStart && iEnd > iInnerStart) { iEnd = iInnerStart - 1; }
                            if (iStart < iWhereStart && iEnd > iWhereStart) { iEnd = iWhereStart - 1; }
                            if (iStart < iOrderbyStart && iEnd > iOrderbyStart) { iEnd = iOrderbyStart - 1; }
                            //
                            if (iEnd - iStart > 6)
                            {
                                strField = strMySQl.Substring(iStart + 7, iEnd - iStart - 6 - 1).Trim();
                                //RemakeFields: rebuild every field
                                if (strField.StartsWith("*") == false && strField.StartsWith("all") == false)
                                {
                                    strChar = String.Empty;
                                    strField += ",";
                                    i = GetSqlKeywordPos(strField, ",");

                                    while (i > -1)
                                    {
                                        if (i == 0)
                                        {
                                            strField = strField.Remove(0, 1);
                                        }
                                        else
                                        {
                                            if (strField.Substring(0, i).Trim() != String.Empty)
                                            {
                                                if (GetSqlKeywordPos(strField.Substring(0, i).Trim(), "as") > 0)
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                    strFieldArray += strField.Substring(0, i).Trim() + "?";
                                                }
                                                else if ((GetSqlKeywordPos(strField.Substring(0, i).Trim(), "distinct") > 0))
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                    strFieldArray += strField.Substring(0, i).Trim() + "?";
                                                }
                                                else if (strField.Substring(0, i).Trim().StartsWith("[") == true && strField.Substring(0, i).Trim().EndsWith("]") == true)
                                                {
                                                    strChar += strField.Substring(0, i).Trim() + ",";
                                                    strFieldArray += strField.Substring(0, i).Trim() + "?";
                                                }
                                                //else if(strField.IndexOf(".") > -1)
                                                //{
                                                //    strChar=strField.Replace(".","")+",";
                                                //}
                                                else if ((strField.Substring(0, i).Trim().IndexOf(".") > -1) && (strField.Substring(0, i).IndexOf(".") < strField.Substring(0, i).Trim().Length))
                                                {
                                                    //                                                    strChar += Left(Trim(Left(strField, i - 1)), InStr(1, Trim(Left(strField, i - 1)), "."));
                                                    //                                                    strChar += Right(Trim(Left(strField, i - 1)), Len(Trim(Left(strField, i - 1))) - InStr(1, Trim(Left(strField, i - 1)), ".")) + ",";

                                                    strChar += strField.Substring(0, i).Trim().Substring(0, strField.Substring(0, i).Trim().IndexOf("."));
                                                    strFieldArray += strField.Substring(0, i).Trim().Substring(0, strField.Substring(0, i).Trim().IndexOf("."));
                                                    strChar += strField.Substring(0, i).Trim().Substring(strField.Substring(0, i).Trim().Length - (strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")), strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")) + ",";
                                                    strFieldArray += strField.Substring(0, i).Trim().Substring(strField.Substring(0, i).Trim().Length - (strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")), strField.Substring(0, i).Trim().Length - strField.Substring(0, i).Trim().IndexOf(".")) + "?";
                                                }
                                                else
                                                {
                                                    strChar += "[" + strField.Substring(0, i).Trim() + "],";
                                                    strFieldArray += "[" + strField.Substring(0, i).Trim() + "]?";
                                                }
                                                iFieldCount++;

                                            }
                                            strField = strField.Substring(i + 1).Trim();

                                        }
                                        i = GetSqlKeywordPos(strField, ",");

                                    }
                                    if (strChar == String.Empty)
                                    {
                                        strField = String.Empty;
                                    }
                                    else
                                    {
                                        strField = strChar;
                                        while (strField.EndsWith("\t") || strField.EndsWith("\n") || strField.EndsWith(","))
                                        {
                                            strField = strField.Remove(strField.Length - 1, 1);
                                        }
                                    }

                                }
                                //

                                if (strField.Length != 0)
                                {
                                    strMain = "select " + strField + " from " + strTableName;
                                    strResult = strMain;
                                }

                                if (strFieldArray.Length != 0)
                                {
                                    strFieldArray = strFieldArray.TrimEnd('?');
                                    fieldArray = strFieldArray.Split('?');
                                }
                            }
                        }
                    }
                    #endregion ***
                }
                else if (sqlOption == SqlOption.SqlPartAll)
                {
                    #region ***Get All Sql
                    strMain = GetSqlParts(strMySQl, SqlOption.SqlPartMain);
                    if (strMain.Length != 0)
                    {
                        //
                        strInner = GetSqlParts(strMySQl, SqlOption.SqlPartInner);
                        strWhere = GetSqlParts(strMySQl, SqlOption.SqlPartWhere);
                        strOrderby = GetSqlParts(strMySQl, SqlOption.SqlPartOrderBy);
                        strResult = strMain + String.Format(" {0} {1} {2} ", strInner, strWhere, strOrderby);
                    }
                    #endregion ***
                }

            }

            return strResult;
        }

        #endregion

        #region Get field real and alias from sql
        public static string[] GetFieldRealAndAliasName(string strSql)
        {
            string strMainSql = "";
            string strRealAndAliasName = "";
            int iASPosition = -1;
            string[] strArrField = null;
            string[] strArrRealAndAliasName = null;
            int i = 0;

            strMainSql = GetSqlParts(strSql, SqlOption.SqlPartMain, ref strArrField);
            iASPosition = strMainSql.IndexOf(" as ", StringComparison.CurrentCultureIgnoreCase);
            if (iASPosition != -1)
            {
                //if field have alias, get FieldRealAndAliasName Array
                for (i = 0; i < strArrField.Length; i++)
                {
                    if (strArrField[i].IndexOf(" as ", StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                        strRealAndAliasName += strArrField[i] + "?";
                    }
                }

                strRealAndAliasName = strRealAndAliasName.TrimEnd('?');
                if (strRealAndAliasName.Trim() != "")
                    strArrRealAndAliasName = strRealAndAliasName.Split('?');
            }

            return strArrRealAndAliasName;
        }
        #endregion

        #endregion

        #region public int GetSqlKeywordPos() +1
        /// <summary>
        /// Created at 7/10/2005
        /// Function:Get a key word absolute position from a SQL string
        ///        this key word does not in "( )" or "[ ]"
        ///         this key word maybe a separator ","
        /// Return:If find return start position(is >=1), not find return 0
        /// </summary>
        /// <param name="strSQl"></param>
        /// <param name="strKeyword"></param>
        /// <param name="iStart"></param>
        /// <returns></returns>
        ////public static  int GetSqlKeywordPos(string strSQl ,string strKeyword , int iStart) 
        ////{			
        ////    int iPos = -1; //current pos
        ////    int iPrPos = 0; //previous pos
        ////    int iCLCount = -1 ;// "(" count
        ////    int iCRCount = -1 ;// ")" count
        ////    int iSLCount = -1 ;// "[" count
        ////    int iSRCount = -1 ;// "]" count
        ////    int iReturn = 0 ;
        ////    //
        ////    string strKey = String.Empty;
        ////    string strChar = String.Empty;
        ////    //
        ////    bool bIsSelf = false;//check key word is or not included by other word
        ////    //
        ////    strSQl = strSQl.ToUpper();
        ////    strKeyword = strKeyword.ToUpper();

        ////    if(strSQl != null && strSQl.Length != 0 && strKeyword != null && strKeyword.Length != 0)
        ////    {
        ////        iPrPos = iStart;
        ////        strKey = strKeyword.Trim();
        ////        iPos = strSQl.IndexOf(strKeyword,iStart);

        ////        if(iPos != -1)
        ////        {
        ////            while(iPos > -1)
        ////            {
        ////                bIsSelf = true;

        ////                if(strKey != ",")//
        ////                {
        ////                    if(iPos > 0)
        ////                    {
        ////                        strChar = strSQl.Substring(iPos -1,1);
        ////                        if(strChar != " " && strChar != "\n" && strChar != "\t"&&
        ////                            strChar != "," && strChar != "." && strChar != "[" &&
        ////                            strChar != "]" && strChar != "(" && strChar != ")")
        ////                        {
        ////                            bIsSelf = false;
        ////                        }
        ////                    }

        ////                    if(bIsSelf == true && iPos + strKey.Length -1 < strSQl.Length )
        ////                    {
        ////                        strChar = strSQl.Substring(iPos + strKey.Length ,1);
        ////                        if(strChar != " " && strChar != "\n" && strChar != "\t"&&
        ////                            strChar != "," && strChar != "." && strChar != "[" &&
        ////                            strChar != "]" && strChar != "(" && strChar != ")")
        ////                        {
        ////                            bIsSelf = false;
        ////                        }
        ////                    }
        ////                }

        ////                if( bIsSelf == false)
        ////                {
        ////                    iPos = strSQl.IndexOf(strKey ,iPos +1 );
        ////                }

        ////                for(int i = iPrPos ; i< iPos -1 ;i++)
        ////                {
        ////                    strChar = strSQl.Substring( i, 1);
        ////                    switch (strChar )
        ////                    {
        ////                        case "(":
        ////                            iCLCount = iCLCount + 1;
        ////                            break;
        ////                        case ")":
        ////                            iCRCount = iCRCount + 1;
        ////                            break;
        ////                        case "[":
        ////                            iSLCount = iSLCount + 1;
        ////                            break;
        ////                        case "]":
        ////                            iSRCount = iSRCount + 1;
        ////                            break;
        ////                    }
        ////                }

        ////                if(iCLCount == iCRCount && iSLCount == iSRCount)
        ////                {
        ////                    iReturn = iPos;
        ////                }
        ////                else
        ////                {
        ////                    iPrPos = iPos;
        ////                    iPos = strSQl.IndexOf(strKey,iPos + 1 );
        ////                }
        ////            }
        ////        }
        ////    }
        ////    return iReturn;
        ////}
        public static int GetSqlKeywordPos(string strSQl, string strKeyword, int intStart)
        {
            int returnValue;
            //*********************************************************************
            //Function:Get a key word absolute position from a SQL string
            //         this key word does not in "( )" or "[ ]"
            //         this key word maybe a separator ","
            //Return:If find return start position(is >=1), not find return 0
            //Author:Wang Gang 2000/11/16
            //*********************************************************************
            int i;
            int intPos = -1; //current pos
            int intPrPos = 0; //previous pos
            int intCLCount = -1; // "(" count
            int intCRCount = -1; // ")" count
            int intSLCount = -1; // "[" count
            int intSRCount = -1; // "]" count

            //int iPos = -1; //current pos
            //int iPrPos = 0; //previous pos
            //int iCLCount = -1;// "(" count
            //int iCRCount = -1;// ")" count
            //int iSLCount = -1;// "[" count
            //int iSRCount = -1;// "]" count
            //int iReturn = 0;

            string strKey;
            string strChar;
            bool blnIsSelf; //check key word is or not included by other word

            returnValue = -1;
            if (strSQl == null || strSQl.Trim() == "")
            {
                return returnValue;
            }

            if (strKeyword == null || strKeyword.Trim() == "")
            {
                return returnValue;
            }
            intPrPos = intStart;
            strKeyword = strKeyword.ToUpper().Trim();
            strKey = strKeyword.Trim().ToUpper();
            strSQl = strSQl.Trim().ToUpper();
            intPos = strSQl.IndexOf(strKey, StringComparison.CurrentCultureIgnoreCase);// Strings.InStr(intStart, strSQl, strKey, CompareMethod.Text);
            if (intPos == -1)
            {
                return returnValue;
            }

            while (intPos >= 0)
            {
                //check key word is or not included by other word
                blnIsSelf = true;
                if (strKey != ",") // "," no need check
                {
                    //check left char , it must be " ",or "()[]" ",.", or key word pos =1
                    if (intPos > 1)
                    {
                        strChar = strSQl.Substring(intPos - 1, 1);
                        if (strChar != " " && strChar != "\n" && strChar != "\t" &&
                           strChar != "," && strChar != "." && strChar != "[" &&
                           strChar != "]" && strChar != "(" && strChar != ")")
                        {
                            blnIsSelf = false;
                        }
                    }
                    //check right char, it must be " ", or key word at last
                    if (blnIsSelf && intPos + strKey.Length - 1 < strSQl.Length)
                    {
                        strChar = strSQl.Substring(intPos + strKey.Length, 1);
                        if (strChar != " " && strChar != "\n" && strChar != "\t" &&
                           strChar != "," && strChar != "." && strChar != "[" &&
                           strChar != "]" && strChar != "(" && strChar != ")")
                        {
                            blnIsSelf = false;
                        }
                    }
                }

                if (!blnIsSelf)
                {
                    //is not a single word, must find again
                    intPos = strSQl.IndexOf(strKey, intPos + 1, StringComparison.CurrentCultureIgnoreCase);  //    (short) Strings.InStr(intPos + 1, strSQl, strKey, CompareMethod.Text);
                }
                else
                {
                    //is a single word, check is or not included by "(" ,")", "[", "]"
                    //calculate "(" ,")", "[", "]" count
                    for (i = intPrPos; i <= intPos - 1; i++)
                    {
                        strChar = strSQl.Substring(i, 1);
                        switch (strChar)
                        {
                            case "(":

                                intCLCount = intCLCount + 1;
                                break;
                            case ")":

                                intCRCount = intCRCount + 1;
                                break;
                            case "[":

                                intSLCount = intSLCount + 1;
                                break;
                            case "]":

                                intSRCount = intSRCount + 1;
                                break;
                            default:

                                break;
                        }
                    }
                    //compare intCLCount and intCRCount,intSLCount and intSRCount
                    //if intCLCount=intCRCount and intSLCount=intSRCount
                    //means find is successfully
                    if (intCLCount == intCRCount && intSLCount == intSRCount)
                    {
                        returnValue = intPos;
                        return returnValue;
                    }
                    else
                    {
                        intPrPos = intPos;
                        intPos = strSQl.IndexOf(strKey, intPos + 1, StringComparison.CurrentCultureIgnoreCase);  // Strings.InStr(intPos + 1, strSQl, strKey, CompareMethod.Text);
                    }
                }
            }
            return returnValue;
        }

        public static int GetSqlKeywordPos(string strSQl, string strKeyword)
        {
            return GetSqlKeywordPos(strSQl, strKeyword, 0);

        }
        #endregion

        #region public static string GetNext()
        public static string GetNext(string strFormChar)
        {
            bool bValid = false;
            bool bAdd = false;
            Char[] CharArray;
            string strReturn = String.Empty;

            if (strFormChar.Length == 0)
            {
                strReturn = "1";
            }
            CharArray = strFormChar.ToCharArray();

            for (int i = 0; i < CharArray.Length; i++)
            {
                if ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf(CharArray[i]) != -1)
                {
                    bValid = true;
                    if (CharArray[i] == '9')
                    {
                        CharArray[i] = 'A';
                        break;
                    }
                    else if (CharArray[i] == 'Z')
                    {
                        bAdd = true;
                    }
                    else
                    {
                        CharArray[i] = (char)((short)CharArray[i] + 1);
                        bAdd = false;
                        break;
                    }

                }
            }

            if (bValid)
            {
                foreach (char c in CharArray)
                {
                    strReturn += c.ToString();
                }
                if (bAdd)
                {
                    strReturn += "0";
                }

            }
            else
            {
                strReturn = strFormChar + "1";
            }

            return strReturn;


        }
        #endregion

        #region public static string FormatWithBlank()
        public static string FormatWithBlank(string strField_Char, int intField_length)
        {

            string strForm_char = strField_Char.Trim();
            int iDiff = intField_length - strForm_char.Length;

            if (BaseFunctions.IsNumeric(strForm_char))
            {
                for (int i = 0; i < iDiff; i++)
                {
                    strForm_char = " " + strForm_char;
                }
            }
            return strForm_char.ToUpper();
        }
        #endregion

        #region GetSubCondition
        public static string GetSubCondition(string strSubType)
        {
            string strCodition = "";

            if (strSubType == "1")
                strCodition = " SwitchSys='GL'";
            else if (strSubType == "2")
                strCodition = " SwitchSys='AP'";
            else if (strSubType == "3")
                strCodition = " SwitchSys='AR'";
            else if (strSubType == "4")
                strCodition = " SwitchSys='OE'";
            else if (strSubType == "5")
                strCodition = " SwitchSys='IM'";
            else if (strSubType == "6")
                strCodition = " SwitchSys='PO'";
            else if (strSubType == "7")
                strCodition = " SwitchSys='RM'";
            else if (strSubType == "8")
                strCodition = " SwitchSys='M'";
            else if (strSubType == "9")
                strCodition = " SwitchSys='TP'";
            else if (strSubType == "99")
                strCodition = "";

            if (strCodition != "")
            {
                strCodition = " Where " + strCodition;
            }

            return strCodition;
        }
        #endregion

        #region public static string FormatWithZero()
        public static string FormatWithZero(string strField_Char, int intField_length)
        {

            string strForm_char = strField_Char.Trim();
            int iDiff = intField_length - strForm_char.Length;

            if (BaseFunctions.IsNumeric(strForm_char))
            {
                for (int i = 0; i < iDiff; i++)
                {
                    strForm_char = "0" + strForm_char;
                }
            }
            return strForm_char.ToUpper();
        }
        #endregion

        #region SplitTally
        public static bool SplitTally(ref string[] strTallyArray, string strTally, int intLength, bool blnTrim)
        {
            int i;
            int intUbound;

            if (strTally.IndexOf(Environment.NewLine) > 0)
            {
                strTallyArray = BaseFunctions.Split(strTally, Environment.NewLine);
                return true;
            }

            ArrayList alTally = new ArrayList();
            intUbound = 0;
            strTally = strTally.Trim();
            if (blnTrim)
            {
                while (strTally.IndexOf("  ") > 0)
                {
                    strTally = strTally.Replace("  ", " ");
                }
            }

            strTally = strTally.Trim();
            intUbound = 0;
            while (!(strTally.Length <= intLength))
            {

                i = strTally.LastIndexOf(" ", intLength, intLength);
                if (i > 0)
                {
                    alTally.Add(strTally.Substring(0, i));
                    strTally = strTally.Substring(i + 1).Trim();
                }
                else
                {
                    alTally.Add(strTally.Substring(0, intLength));
                    strTally = strTally.Substring(intLength + 1).Trim();
                }
                intUbound = intUbound + 1;
            }


            if (strTally.Trim() != "")
            {
                alTally.Add(strTally);
                intUbound = intUbound + 1;
            }

            strTallyArray = new string[intUbound];
            i = 0;
            foreach (object str in alTally)
            {
                strTallyArray[i] = str.ToString();
                i++;
            }

            return true;


        }
        #endregion SplitTally

        #region  Get LookUp SQL
        //public static string GetLookUpSQL(string strTableName)
        //{
        //    return GetLookUpSQL(strTableName, 0, false);
        //}
        //public static string GetLookUpSQL(string strTableName, int iParameter)
        //{
        //    return GetLookUpSQL(strTableName, iParameter, true);
        //}
        //public static string GetLookUpSQL(string strTableName, int iParameter, bool blnIsForOverView)
        //{
        //    string strPre = "", strSql = "";
        //    if (strTableName == null) return "";
        //    if (strTableName.Substring(0, 1).ToLower() == "m")
        //    {
        //        strPre = "MF";
        //    }            
        //    else
        //    {
        //        strPre = strTableName.Substring(0, 2).ToUpper();
        //    }
        //    try
        //    {
        //        Type typeDAL = Type.GetType("WP." + strPre + ".DataAccess." + strTableName + "DAL," + "WP." + strPre + ".DataAccess", true, true);
        //        WP.Commons.IDataAccess iDAL = (WP.Commons.IDataAccess)Activator.CreateInstance(typeDAL);
        //        strSql = iDAL.SQLList(iParameter);
        //        if (blnIsForOverView)
        //        {
        //            string strDefSql = DataFunctions.GetFieldValue("mUserListViewDefine", "SqlString", "UserName='" + SysVar.UserName + "' and TableName='" + strTableName + "' and Parameter=" + iParameter.ToString());
        //            if (strDefSql.Trim() != "")
        //            {
        //                strSql = BaseFunctions.GetSqlParts(strDefSql, SqlOption.SqlPartMain) + BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere) + BaseFunctions.GetSqlParts(strDefSql, SqlOption.SqlPartOrderBy);
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        strSql = "";
        //    }

        //    if (strSql == "")
        //    {
        //        return DataFunctions.GetSqlByKeySort("select * from " + strTableName);
        //    }

        //    return strSql;
        //}
        #endregion



        #region IsNumSql
        public static string IsNumSql(string strFldName)
        {
            string strOrigFldValues = strFldName;
            string strNewFldValues = "";
            strNewFldValues = "Replace(" + strOrigFldValues + ",'D','!')";
            strNewFldValues = "Replace(" + strNewFldValues + ",'E','!')";
            strNewFldValues = "Replace(" + strNewFldValues + ",',','!')";
            strNewFldValues = "case when ltrim(rtrim(" + strNewFldValues + "))='.' then replace(" + strNewFldValues + ",'.','!') else " + strNewFldValues + " end";
            return strNewFldValues;
        }
        #endregion


        #region is click DataGrid Cell
        public static bool IsDatagridCell(DataGridEx dgList, System.Windows.Forms.MouseEventArgs e)
        {
            bool blnIsCell = false;
            DataGridView myGrid = (DataGridView)dgList;
            System.Windows.Forms.DataGridView.HitTestInfo hti;
            hti = myGrid.HitTest(e.X, e.Y);
            switch (hti.Type)
            { 
                case System.Windows.Forms.DataGridViewHitTestType.None :
                case DataGridViewHitTestType.ColumnHeader:                   
                    break ;
                case DataGridViewHitTestType.Cell :
                case DataGridViewHitTestType.RowHeader :
                    blnIsCell = true;
                    break;
            }
            return blnIsCell;
        
        }
        #endregion
        /// <summary>
        /// because of rounding , program will assume a Min value to calculate quantity .
        /// </summary>
        /// <param name="strQtyUnit"></param>
        /// <returns></returns>
        public static double PermitIgnoreMinQty(string strQtyUnit)
        {
            switch (strQtyUnit.Trim().ToUpper())
            {
                case "BF":
                    return 5;
                default:
                    return 0;

            }
            return 0;
        }

        public static bool SureDelete()
        {
            if (MessageBox.Show("您确定删除此条记录？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                return true;
            else
                return false;
        }

      

       

        #endregion

        #region deal with data type

        #region Check whether a string value is date value
        /// <summary>
        /// Check whether a string value is date value  
        /// </summary>
        /// <param name="Value">Checked string</param>
        public static bool IsDate(object Value)
        {
            if (Value == null)
                return false;
            else
                return IsDate(Value.ToString());
        }
        public static bool IsDate(string Value)
        {
            if (Value == null || Value == string.Empty)
            {
                return false;
            }
            else
            {
                try
                {
                    DateTime.Parse(Value);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }
        #endregion

        #region Check whether a string value is numeric value
        /// <summary>
        /// Check whether a string value is numeric value  
        /// </summary>
        /// <param name="Value">Checked string</param>
        public static bool IsNumeric(string Value)
        {
            return IsNumeric(Value, false);
        }

        public static bool IsNumeric(string Value, bool bIncludeSpecString)
        {
            if (bIncludeSpecString)
            {
                Value = Value.Replace("$", "").Replace("(", "").Replace(")", "").Trim();
            }

            string strValue = CvtFunc.ToString(Value);

            int iLength = strValue.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;

            if (strValue == null || strValue == string.Empty || iLength == 0 || iLength > 2)
            {
                return false;
            }
            else
            {
                strValue = strValue.Replace(",", "");

                if (strValue.Substring(0, 1) == "-")
                {
                    strValue = strValue.Substring(1, strValue.Length - 1);
                    if (strValue == "") return false;
                }

                foreach (char c in strValue.ToCharArray())
                {
                    if (!(char.IsNumber(c) || c == '.'))
                    {
                        return false;
                    }
                }

                if (strValue.IndexOf("..") > 0) return false;
                return true;
            }

        }
        #endregion

        #region Check whether a string value is double value
        /// <summary>
        /// Check whether a string value is double value  
        /// </summary>
        /// <param name="Value">Checked string</param>
        public static bool IsDouble(string Value)
        {


            if (Value == null || Value == string.Empty)
            {
                return false;
            }
            else
            {
                if (Value.Substring(0, 1) == "-")
                {
                    Value = Value.Substring(1, Value.Length - 1);
                }

                foreach (char c in Value.ToCharArray())
                {
                    if (!(char.IsNumber(c) || c == '.' || c == ','))
                    {
                        return false;
                    }
                }
                return true;
            }
        }
        #endregion

        #region Check whether a string value is inteter value
        /// <summary>
        /// Check whether a string value is inteter value  
        /// </summary>
        /// <param name="Value">Checked string</param>
        public static bool IsInt(string Value)
        {
            if (Value == null || Value == string.Empty)
            {
                return false;
            }
            else
            {

                foreach (char c in Value.ToCharArray())
                {
                    if (!char.IsNumber(c))
                        return false;
                }
                return true;
            }
        }
        #endregion

        #region Cast object to duble,check the null and DBNull
        /// <summary>
        /// Cast object to duble,check the null and DBNull
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double CastToDouble(object obj)
        {
            if (obj == null || obj == DBNull.Value || obj.ToString() == "")
            {
                return 0;
            }
            else
            {
                return double.Parse(obj.ToString());
            }
        }
        #endregion

        #region Cast object to int,check the null and DBNull
        /// <summary>
        /// Cast object to int,check the null and DBNull
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int CastToInt(object obj)
        {
            if (obj == null || obj == DBNull.Value || obj.ToString() == "")
            {
                return 0;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        #endregion

        #region split a string with separator
        public static string[] Split(string strData, string strSeparator)
        {
            int iCount = 0;
            int iPos1 = 0, iPos2 = 0;
            int iSepLength = 0;
            string[] strSplit = null;

            if (strData == null || strSeparator == null)
                return null;
            else
            {
                iSepLength = strSeparator.Length;

                while (iPos1 >= 0)
                {
                    iPos1 = strData.IndexOf(strSeparator, iPos2);
                    if (iPos1 >= 0)
                    {
                        iPos2 = iPos1 + iSepLength;
                    }
                    if (iPos1 >= 0)
                    {
                        iCount++;
                    }
                }

                if (iPos2 < strData.Length)
                {
                    iCount++;
                }
                strSplit = new string[iCount];

                iCount = 0; iPos1 = 0; iPos2 = 0;

                while (iPos1 >= 0)
                {
                    iPos1 = strData.IndexOf(strSeparator, iPos2);
                    if (iPos1 >= 0)
                    {
                        strSplit[iCount] = strData.Substring(iPos2, iPos1 - iPos2);
                        iPos2 = iPos1 + iSepLength;
                    }

                    if (iPos1 >= 0)
                    {
                        iCount++;
                    }
                }

                if (iPos2 < strData.Length)
                {
                    strSplit[iCount] = strData.Substring(iPos2, strData.Length - iPos2);
                }

                return strSplit;
            }
        }
        #endregion

        #region Convert Array to DataTable
        public static DataTable ArrayToDataTable(string[] FieldNameArray, string[] ValueArray1, string[] ValueArray2)
        {
            DataTable dt = null;
            DataRow dr = null;

            if ((FieldNameArray.Length >= 2) && (ValueArray1.Length == ValueArray2.Length))
            {
                dt = new DataTable("NewTable");
                dt.Columns.Add(FieldNameArray[0].ToString());
                dt.Columns.Add(FieldNameArray[1].ToString());

                for (int i = 0; i < ValueArray1.Length; i++)
                {
                    dr = dt.NewRow();

                    dr[FieldNameArray[0].ToString()] = ValueArray1[i].ToString();
                    dr[FieldNameArray[1].ToString()] = ValueArray2[i].ToString();
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        #endregion

        #region FormatDate
        //format date type data to long date type
        public static string FormatDate(DateTime dt)
        {
            string strFormatDate = "";

            strFormatDate = dt.ToString(SystemDateOption.optDateFmtMDY, System.Globalization.DateTimeFormatInfo.InvariantInfo);

            return strFormatDate;
        }

        public static string FormatDate(string dt)
        {
            string strFormatDate = "";

            if (dt != "" && dt.Trim() != "/  /")
                strFormatDate = DateTime.Parse(dt).ToString(SystemDateOption.optDateFmtMDY, System.Globalization.DateTimeFormatInfo.InvariantInfo);

            return strFormatDate;
        }

        public static string FormatDate(string dt, DateFormatOption optFormat)
        {
            string strFormatDate = "";
            if (dt.Trim() == "/  /" || dt.Trim() == "") return strFormatDate;
            strFormatDate = DateTime.Parse(dt).ToString(SystemDateOption.GetFormat(optFormat), System.Globalization.DateTimeFormatInfo.InvariantInfo);

            return strFormatDate;
        }
        #endregion

      

        #region Input string:'Yes' or 'No',"True" or 'False', Return bool: True or False
        public static bool GetBoolValue(string strValue)
        {
            bool bReturn = false;
            if (strValue.ToUpper().Trim() == "YES" || strValue.ToUpper().Trim() == "TRUE")
            {
                bReturn = true;
            }
            return bReturn;
        }
        #endregion

        #region Get Days
        /// <summary>
        /// Get Days: if strEndDate > strStartDate, than return value >0 else  if strEndDate = strStartDate, than return value =0 else return value <0
        /// </summary>
        /// <param name="strStartDate"></param>
        /// <param name="strEndDate"></param>
        /// <returns></returns>
        public static int CompareDate(string strStartDate, string strEndDate)
        {
            DateTime dtStartDate, dtEndDate;
            TimeSpan timeSpan;

            dtStartDate = Convert.ToDateTime(strStartDate);
            dtEndDate = Convert.ToDateTime(strEndDate);

            timeSpan = dtEndDate.Subtract(dtStartDate);

            return timeSpan.Days;
        }
        #endregion

        #region StringUtil
        public static string Space(int i)
        {
            string s = "";
            for (int j = 0; j < i; j++)
            {
                s += " ";
            }
            return s;
        }

        public static int ToInt32(string a_strPara, Int32 a_intDefault)
        {
            if (a_strPara == null) return a_intDefault;
            if (!IsInt(a_strPara)) return a_intDefault;
            try
            {
                return Convert.ToInt32(a_strPara);
            }
            catch
            {
                return a_intDefault;
            }
        }

        ////public static DateTime ToDateTime(string a_strPara, DateTime a_datDefault)
        ////{
        ////    if (a_strPara==null) return a_datDefault;
        ////    try
        ////    {
        ////        return DateTime.Parse(a_strPara);
        ////    }
        ////    catch
        ////    {
        ////        return a_datDefault;
        ////    }
        ////}

        ////public static int ToInt32(Object a_strPara, Int32 a_intDefault)
        ////{
        ////    if (a_strPara==null) return a_intDefault;
        ////    try
        ////    {
        ////        return Convert.ToInt32(a_strPara);
        ////    }
        ////    catch
        ////    {
        ////        return a_intDefault;
        ////    }
        ////}
        ////public static decimal ToDecimal(Object a_strPara, decimal a_intDefault)
        ////{
        ////    if (a_strPara==null) return a_intDefault;
        ////    try
        ////    {
        ////        return Convert.ToDecimal(a_strPara);
        ////    }
        ////    catch
        ////    {
        ////        return a_intDefault;
        ////    }
        ////}

        ////public static byte ToByte(Object a_strPara, byte a_intDefault)
        ////{
        ////    if (a_strPara==null) return a_intDefault;
        ////    try
        ////    {
        ////        return Convert.ToByte(a_strPara);
        ////    }
        ////    catch
        ////    {
        ////        return a_intDefault;
        ////    }
        ////}		

        //////		public static string CheckNull(string a_strPara, string a_strDefault)
        //////		{
        //////			if (a_strPara==null) return a_strDefault;
        //////			else return a_strPara;
        //////		}
        ////public static string CheckNull(Object a_strPara, string a_strDefault)
        ////{
        ////    if (a_strPara==null) return a_strDefault;
        ////    else return a_strPara.ToString();
        ////}
        ////public static float ToSingle(Object a_objObject, float a_sngDefault)
        ////{
        ////    try
        ////    {
        ////        return Convert.ToSingle(a_objObject);
        ////    }
        ////    catch
        ////    {
        ////        return a_sngDefault;
        ////    }
        ////}

        ////public static string ToString(Object a_objObject)
        ////{
        ////    return ToString(a_objObject, "", "");
        ////}

        ////public static string ToString(Object a_objObject, string a_strDefault)
        ////{
        ////    return ToString(a_objObject, "", a_strDefault);
        ////}

        ////public static string ToString(Object a_objObject, string a_strformat, string a_strDefault)
        ////{
        ////    string strValue="";
        ////    try
        ////    {
        ////        if (a_objObject == null)
        ////            return a_strDefault;
        ////        else
        ////        {
        ////            if (a_strformat == "")
        ////            {
        ////                strValue = a_objObject.ToString();
        ////            }
        ////            else
        ////            {
        ////                Type sType = a_objObject.GetType();
        ////                switch (sType.ToString())
        ////                {
        ////                    //case "System.Byte":
        ////                    //    break;
        ////                    case "System.DateTime":
        ////                        DateTime dtValue = Convert.ToDateTime(a_objObject);
        ////                        strValue = dtValue.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Int16":
        ////                        Int16 I16Value = Convert.ToInt16(a_objObject);
        ////                        strValue = I16Value.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Int32":
        ////                        Int32 I32Value = Convert.ToInt32(a_objObject);
        ////                        strValue = I32Value.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Int64":
        ////                        Int64 I64Value = Convert.ToInt64(a_objObject);
        ////                        strValue = I64Value.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Decimal":
        ////                        Decimal decValue = Convert.ToDecimal(a_objObject);
        ////                        strValue = decValue.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Single":
        ////                        Single sValue = Convert.ToSingle(a_objObject);
        ////                        strValue = sValue.ToString(a_strformat);
        ////                        break;
        ////                    case "System.Double":
        ////                        Double dValue = Convert.ToDouble(a_objObject);
        ////                        strValue = dValue.ToString(a_strformat);
        ////                        break;
        ////                    default:
        ////                        strValue = a_objObject.ToString();
        ////                        break;
        ////                }
        ////            }
        ////        }
        ////        return strValue;
        ////    }
        ////    catch
        ////    {
        ////        return a_strDefault;
        ////    }
        ////}

        /////// <summary>
        /////// 将数字转换成定长的字符串，如果长度不够，前面补0
        /////// </summary>
        /////// <param name="num">要转换的数字</param>
        /////// <param name="len">要返回字符串的长度</param>
        /////// <returns>定长的字符串，如果长度超过指定的长度，不进行截断操作</returns>
        ////public static string FixLen(int num,int len)
        ////{
        ////    string rtn = num.ToString().Trim();
        ////    if (rtn.Length>=len) return rtn;
        ////    else 
        ////    {
        ////        int olen = rtn.Length;
        ////        for (int i=0;i<len-olen;i++)
        ////        {
        ////            rtn = "0" + rtn;
        ////        }
        ////        return rtn;
        ////    }
        ////}
        ////public static string FixLen(int num,int len,char fileStr)
        ////{
        ////    string rtn = num.ToString().Trim();
        ////    if (rtn.Length>=len) return rtn;
        ////    else 
        ////    {
        ////        int olen = rtn.Length;
        ////        for (int i=0;i<len-olen;i++)
        ////        {
        ////            rtn = fileStr + rtn;
        ////        }
        ////        return rtn;
        ////    }
        ////}
        ////public static string FixLen(decimal num,int len,char fileStr)
        ////{
        ////    string rtn = num.ToString().Trim();
        ////    if (rtn.Length>=len) return rtn;
        ////    else 
        ////    {
        ////        int olen = rtn.Length;
        ////        for (int i=0;i<len-olen;i++)
        ////        {
        ////            rtn = fileStr + rtn;
        ////        }
        ////        return rtn;
        ////    }
        ////}
        ////public static string FixLen(Object num,int len,char fileStr)
        ////{
        ////    string rtn = num.ToString().Trim();
        ////    if (rtn.Length>=len) return rtn;
        ////    else 
        ////    {
        ////        int olen = rtn.Length;
        ////        for (int i=0;i<len-olen;i++)
        ////        {
        ////            rtn = fileStr + rtn;
        ////        }
        ////        return rtn;
        ////    }
        ////}
        ////public	static	string GetFileExtName(string strFileName)
        ////{
        ////    int iPos = strFileName.LastIndexOf('.');
        ////    if (iPos==-1) return "";
        ////    return	strFileName.Substring(iPos,strFileName.Length-iPos);    
        ////}
        ////public	static	string GetFileBaseName(string strFileName)
        ////{
        ////    int iPos = strFileName.LastIndexOf('.');
        ////    if (iPos==-1) return strFileName;
        ////    return	strFileName.Substring(0,iPos);
        ////}
        ////public	static	int	CodeToID(string a_strID,int defID)
        ////{
        ////    string mstrTemp;
        ////    int mintPoss = a_strID.LastIndexOf("{");
        ////    int mintPose = a_strID.LastIndexOf("}");
        ////    if (mintPoss>-1 && mintPose>-1)
        ////    {
        ////        mstrTemp = a_strID.Substring(mintPoss+1,mintPose-mintPoss-1);
        ////        return ToInt32(mstrTemp,defID);
        ////    }
        ////    else
        ////    {
        ////        return ToInt32(a_strID,defID);
        ////    }
        ////}
        ////public	static	int	CodeToID(string a_strID)
        ////{
        ////    return CodeToID(a_strID,0);
        ////}
        ////public	static	int	GetTopParentIDFromCode(string a_strID)
        ////{
        ////    string mstrTemp;
        ////    int mintPoss = a_strID.IndexOf("{");
        ////    int mintPose = a_strID.IndexOf("}");
        ////    if (mintPoss>-1 && mintPose>-1)
        ////    {
        ////        mstrTemp = a_strID.Substring(mintPoss+1,mintPose-mintPoss-1);
        ////        return ToInt32(mstrTemp,0);
        ////    }
        ////    else
        ////    {
        ////        return ToInt32(a_strID,0);
        ////    }
        ////}
        ////public static string NumToStandard(Object a_objObject, string a_strDefault)
        ////{

        ////    string strReturn;
        ////    int i=0;
        ////    int intLength=0;
        ////    string strNum = Convert.ToString(a_objObject);			
        ////    string strDecimal;
        ////    string strTmpInteger;

        ////    if (a_objObject==null) return a_strDefault;

        ////    try
        ////    {
        ////        i = strNum.IndexOf(".");
        ////        if(i<=0)
        ////        {
        ////            strTmpInteger = strNum;
        ////            strDecimal = "00";
        ////        }
        ////        else
        ////        {
        ////            strTmpInteger = strNum.Substring(0,i);
        ////            strDecimal = strNum.Substring(i+1);
        ////        }

        ////        string strInteger="";
        ////        i=0;
        ////        intLength = strTmpInteger.Length;

        ////        while(intLength>0)
        ////        {
        ////            i += 1;
        ////            strInteger = strTmpInteger.Substring(intLength-1,1) + strInteger;
        ////            if(i==3 && intLength>1)
        ////            {
        ////                strInteger = "," + strInteger;
        ////                i=0;
        ////            }				
        ////            intLength -= 1;
        ////        }

        ////        strReturn = strInteger + "." + strDecimal;
        ////    }
        ////    catch
        ////    {
        ////        strReturn = a_strDefault;
        ////    }
        ////    return strReturn;
        ////}

        ////public static string StandardToNum(Object a_objObject, string a_strDefault)
        ////{
        ////    if (a_objObject==null) return a_strDefault;
        ////    try
        ////    {
        ////        string strReturn = Convert.ToString(a_objObject);
        ////        return strReturn.Replace(",","").Trim();
        ////    }
        ////    catch
        ////    {
        ////        return a_strDefault;
        ////    }
        ////}
        ////public static string GetExceptionMessage(Exception ex)
        ////{
        ////    string a_strMessage;
        ////    if (ex.Message!=null && ex.Message.Length>0)
        ////    {
        ////        int i	= ex.Message.IndexOf("\r");
        ////        int j	= ex.Message.IndexOf("\n");
        ////        i		= System.Math.Min(i,j);
        ////        if (i>0)
        ////            a_strMessage= ex.Message.Substring(0,i);
        ////        else
        ////            a_strMessage= ex.Message;
        ////    }
        ////    else
        ////        a_strMessage = "应用程序发生异常";
        ////    return a_strMessage;
        ////}

        ////public static string FormatNumToMoney(decimal Number)
        ////{

        ////    string strReturn;

        ////    strReturn = Number.ToString("####.00");
        ////    return strReturn;
        ////}
        ////public	static string GetParentCode(string a_strCode)
        ////{
        ////    int intPosBegin;
        ////    intPosBegin	= a_strCode.LastIndexOf("{");
        ////    //intPosEnd	= a_strCode.LastIndexOf("}");
        ////    if (intPosBegin<1) return "";
        ////    return a_strCode.Substring(0,intPosBegin);
        ////}
        #endregion

        #region InStrEx
        public static bool InStrEx(string strInCompStr, string strCompStr)
        {
            return InStrEx(strInCompStr, strCompStr, ",");
        }
        public static bool InStrEx(string strInCompStr, string strCompStr, string strSplit)
        {
            string[] strArrSplit = new string[1];

            strArrSplit[0] = strSplit;

            string[] a = strInCompStr.Split(strArrSplit, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < a.Length; i++)
            {
                if (string.Compare(a[i], strCompStr, StringComparison.CurrentCultureIgnoreCase) == 0) return true;
            }
            return false;
        }
        #endregion

        #region Convert Number to Roma
        public static string CnvNumberToRoma(int intNumber)
        {
            if (intNumber <= 0) return "";

            string[] strRomaArray = new string[] { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" };
            string strCnvNumberToRoma = "";
            int intRoma = intNumber % 10;
            if (intRoma != 0)
            {
                strCnvNumberToRoma = strRomaArray[intRoma];
            }
            intRoma = intNumber / 10;
            for (int i = 1; i <= intRoma; i++)
            {
                strCnvNumberToRoma = strRomaArray[10] + strCnvNumberToRoma;
            }

            return strCnvNumberToRoma;
        }
        #endregion

        #endregion

        #region deal with control
        #region Get MultiTextBox Current Line No
        public static int GetMultiTextBoxCurrentLineNo(string strTextBoxValue)
        {
            string strFind = "\r\n";
            int intLastFind;
            int intNumber;
            intNumber = 1;
            intLastFind = strTextBoxValue.IndexOf(strFind);
            while (intLastFind >= 0)
            {
                intNumber++;
                intLastFind = strTextBoxValue.IndexOf(strFind, intLastFind + 1);
            }
            return intNumber;
        }
        #endregion

       


   
        #endregion

        #region deal with File

        public static bool ValidPath(string strPath)
        {
            // Purpose: budget a path whether user can write permission
            // Inputs: a path
            // Returns: if have return true else return false

            bool bValidPath = true;
            const string strFileName = "CreateJournal";

            strPath = strPath.Trim();
            System.IO.FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(strPath + strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
            }
            catch
            {
                bValidPath = false;
            }
            if (bValidPath)
            {
                fs.Close();
                System.IO.File.Delete(strPath + strFileName);
            }
            return bValidPath;

            //    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
            //    Open strPath & strFileName For Output As #1
            //    Close 1#
            //    Kill strPath & strFileName
            //    Exit Function
            //errdo:
            //    Err.Clear
            //    ValidPath = False
        }
        #endregion

        #region Some Old Func

        #region Convert string to bool db value
        ////public static string ConvertStringToBoolDBValue(string Value)
        ////{
        ////    if(Value==null)
        ////    {
        ////        return null;
        ////    }
        ////    Value=Value.ToLower();

        ////    if(Value=="true"||Value=="yes")
        ////    {
        ////        return "1";
        ////    }
        ////    else if(Value=="false"||Value=="no")
        ////    {
        ////        return "0";
        ////    }
        ////    else
        ////    {
        ////        return null;
        ////    }
        ////}
        #endregion

        #region Add Hide TabPage of TabControl
        ////        public static void AddTabPage(TabControl tbc, TabPage tbpAdd, int OrderIndex)
        ////        {
        ////            TabControl NewTbc = new TabControl();
        ////            int iTabCount = tbc.TabCount;
        ////            int i = 0;
        ////            ArrayList arrayTbp = new ArrayList();

        ////            foreach (TabPage tbp in tbc.TabPages)
        ////            {
        ////                if (i == OrderIndex)
        ////                {
        ////                    arrayTbp.Add(tbpAdd);
        ////                }

        ////                arrayTbp.Add(tbp);
        ////                tbp.Parent = null;

        ////                i++;
        ////            }

        ////            tbc.Refresh();
        ////            foreach (TabPage tbp in arrayTbp)
        ////            {
        ////                tbp.Parent = tbc;
        ////            }
        //////            tbc.Refresh();
        ////        }
        #endregion

        #endregion

        #region Turn Number To Text

        public static string TurnNumberToText(double dblValues, string strUnit)
        {
            return TurnNumberToText(dblValues, strUnit, true, false);
        }

        public static string TurnNumberToText(double dblValues, string strUnit, bool blnTurnText, bool blnPrtPctMiddle)
        {
            string strNumber = string.Empty;
            string strPreNumber = string.Empty;
            string strSufNumber = string.Empty;
            int intPointPos = 0;
            string[] strPSuffix = new string[5];
            int intPer = 0;
            int intLen = 0;
            string tmpstr = string.Empty;
            string tmpStr1 = string.Empty;
            string strReturn = string.Empty;


            //* initial suffix
            strPSuffix[0] = "";
            strPSuffix[1] = "THOUSAND";
            strPSuffix[2] = "MILLION";
            strPSuffix[3] = "BILLION";
            strPSuffix[4] = "TRILLION";

            strNumber = dblValues.ToString();
            intLen = strNumber.Length;

            //*seperate point from number
            intPointPos = strNumber.IndexOf(".");
            if (intPointPos == 0 || intPointPos == -1)
            {
                strPreNumber = strNumber;
                strSufNumber = string.Empty;
                if (blnPrtPctMiddle)
                    strSufNumber = "AND 00/100";
            }
            else
            {
                strPreNumber = strNumber.Substring(0, intPointPos);
                strSufNumber = strNumber.Substring(intPointPos + 1, intLen - intPointPos - 1);
                if (blnTurnText)
                {
                    if (strSufNumber.Length == 1)
                        strSufNumber = strSufNumber.Insert(1, "0") + "/100";
                    else
                        strSufNumber = BaseFunctions.FormatNumeric(strSufNumber, "NS.0") + "/100";

                    if (blnPrtPctMiddle)
                        strSufNumber = " AND " + strSufNumber;
                    else
                        strSufNumber = " " + strSufNumber;

                }
                else
                {
                    strSufNumber = " AND " + strSufNumber + " CENTS";
                }
            }

            //* get string per three number
            if (blnTurnText)
            {
                intLen = strPreNumber.Length;
                intPer = CvtFunc.ToInt(intLen / 3) + CvtFunc.ToInt(CvtFunc.ToInt(intLen % 3) == 0 ? "0" : "1");
                for (int i = 1; i <= intPer; i++)
                {
                    if (strPreNumber.Length <= 0) break;
                    if (strPreNumber.Length >= 0 && strPreNumber.Length < 3)
                        tmpstr = strPreNumber.Substring(0, strPreNumber.Length);
                    else
                        tmpstr = strPreNumber.Substring(strPreNumber.Length - 3, 3);

                    strPreNumber = strPreNumber.Substring(0, strPreNumber.Length - tmpstr.Length);
                    tmpstr = BaseFunctions.ReadThreeNumber(tmpstr) + " " + strPSuffix[i - 1];
                    strReturn = tmpstr + " " + strReturn;
                }

                if (blnPrtPctMiddle)
                    return strReturn.Trim() + strSufNumber + " " + strUnit;
                else
                    return strReturn.Trim() + " " + strUnit + strSufNumber;
                //return strReturn.Trim() + " " + strUnit;
            }
            else
            {
                return strPreNumber.Trim() + " " + strUnit + strSufNumber;
            }

        }

        private static string ReadThreeNumber(string strNumber)
        {
            string[] strPNumber = new string[30];
            string tmpstr = string.Empty;

            strPNumber[0] = "";
            strPNumber[1] = "ONE";
            strPNumber[2] = "TWO";
            strPNumber[3] = "THREE";
            strPNumber[4] = "FOUR";
            strPNumber[5] = "FIVE";
            strPNumber[6] = "SIX";
            strPNumber[7] = "SEVEN";
            strPNumber[8] = "EIGHT";
            strPNumber[9] = "NINE";
            strPNumber[10] = "TEN";
            strPNumber[11] = "ELEVEN";
            strPNumber[12] = "TWELVE";
            strPNumber[13] = "THIRTEEN";
            strPNumber[14] = "FOURTEEN";
            strPNumber[15] = "FIFTEEN";
            strPNumber[16] = "SIXTEEN";
            strPNumber[17] = "SEVENTEEN";
            strPNumber[18] = "EIGHTEEN";
            strPNumber[19] = "NINETEEN";

            //* begin from 22 just for to dispose it easier
            strPNumber[22] = "TWENTY";
            strPNumber[23] = "THIRTY";
            strPNumber[24] = "FORTY";
            strPNumber[25] = "FIFTY";
            strPNumber[26] = "SIXTY";
            strPNumber[27] = "SEVENTY";
            strPNumber[28] = "EIGHTY";
            strPNumber[29] = "NINETY";

            string strReturn = string.Empty;

            if (strNumber.Length == 1)//* only one number
                return strPNumber[CvtFunc.ToInt(strNumber)];
            else
            {
                if (strNumber.Length == 3) //'if there are three number, the first is hundred
                {

                    tmpstr = strPNumber[CvtFunc.ToInt(strNumber.Substring(0, 1))];
                    if (tmpstr.Trim() != string.Empty)
                        strReturn = tmpstr + " HUNDRED";
                }
            }
            strNumber = strNumber.Substring(strNumber.Length - 2, 2);

            if (CvtFunc.ToInt(strNumber) >= 1 && CvtFunc.ToInt(strNumber) < 20)
                tmpstr = strPNumber[CvtFunc.ToInt(strNumber)];
            else
            {
                if (CvtFunc.ToInt(strNumber.Substring(strNumber.Length - 1, 1)) == 0)
                    tmpstr = strPNumber[20 + CvtFunc.ToInt(strNumber.Substring(0, 1))];
                else
                    tmpstr = strPNumber[20 + CvtFunc.ToInt(strNumber.Substring(0, 1))] + "-" +
                        strPNumber[CvtFunc.ToInt(strNumber.Substring(strNumber.Length - 1, 1))];
            }

            if (strReturn.Trim() == string.Empty)
                strReturn = tmpstr;
            else
                strReturn = strReturn + " " + tmpstr;
            return strReturn;
        }

        #endregion

        public static int Mod(int iX, int iY)
        {

            if (iX == 0 || iY == 0)
                return 0;
            return (iX - (iY * (int)(iX / iY)));
        }
        
        public static void ReleaseComObject(object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch { }
            finally
            {
                o = null;
            }
        }
        public static string GetCurrentCusomterName()
        {
            
//            if (SysVar.CodeSignNo == SysVar.DefineCompany.MaritimeForestProducts) return "MaritimeForestProducts";
            return "";
        }


        public static int GetScoreFunction(string strResult)
        { 
            if ( strResult .Trim ().ToUpper()=="A")
                return 0;
            else if (  strResult .Trim ().ToUpper()=="B") 
                return 1;
            else if  ( strResult .Trim ().ToUpper()=="C")
                return 2;
            else if  ( strResult .Trim ().ToUpper()=="D")
                return 3;
            else if  ( strResult .Trim ().ToUpper()=="E")
                return 4;

            return 0;
        }

        public static int GetTHIScoreFunction(string strResult)
        {
            if (strResult.Trim().ToUpper() == "A")
                return 4;
            else if (strResult.Trim().ToUpper() == "B")
                return 0;
            else if (strResult.Trim().ToUpper() == "C")
                return 2;          

            return 0;
        }

        public static string GetExportLineSQL(string strType,string strMenuName, string strFormName)
        {
            DB.DBAccess dbcon = new YT.DB.DBAccess (false ,false );
            string strSQL = "";
            strSQL = "select * from mExportExcel where Type='" + strType + "' and FormName='" + strFormName + "' order by hdrseqno,dtlseqno,rowseqno";
            DataTable dtExport = dbcon.GetDataTable(strSQL);
            if (dtExport != null)
            {
                strSQL = "";
                foreach (DataRow drExport in dtExport.Rows)
                {
                    strSQL += "\r\n" + "max(case when hdrseqno='" + drExport["HdrSeqNo"] + "' and dtlseqno='" + drExport["DtlSeqNo"] + "' and rowno='" + drExport["RowSeqNo"] + "' then result end) as [" + drExport["CHNTitle1"]  + " " + drExport["CHNTitle2"] + " " + drExport["CHNTitle3"] + "],";
                }
                strSQL = strSQL.Substring(0, strSQL.Length - 1);
            }
            dbcon.CloseCon();
            return strSQL;
        }

        public static int GetGridViewNextEnabledEditColumn(DataGridView gridview, int iCurrentColumnIndex)
        {
            return GetGridViewNextEnabledEditColumn(gridview, iCurrentColumnIndex, false);

        }
        public static int GetGridViewNextEnabledEditColumn(DataGridView gridview, int iCurrentColumnIndex, bool blnEnableReadOnly)
        {
            int j = -1;
            string strName = "";
            for (int i = iCurrentColumnIndex + 1; i < gridview.Columns.Count; i++)
            {
                if ((blnEnableReadOnly || !gridview.Columns[i].ReadOnly) && gridview.Columns[i].Visible)
                {
                    strName = gridview.Columns[i].GetType().Name;
                    if (strName != "DataGridViewImageColumn" && strName != "DataGridViewLinkCell")
                    {
                        j = i;
                        break;
                    }
                }
            }

            return j;
        }

        public static string SetCharRow(string strRow)
        {
            if (strRow == "1") return "A";
            if (strRow == "2") return "B";
            if (strRow == "3") return "C";
            if (strRow == "4") return "D";
            if (strRow == "5") return "E";
            if (strRow == "6") return "F";
            if (strRow == "7") return "G";
            if (strRow == "8") return "H";
            return "";
        }
    }

    public class myReverserClass : IComparer
    {

        // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
        int IComparer.Compare( Object x, Object y)
        {
            Control conx = x as Control;
            Control cony = y as Control;
            string strParentX = conx.Parent.Name;
            string strParentY = cony.Parent.Name;
            string strConX = conx.Name;
            string strConY = cony.Name;
            if (conx.Parent == cony.Parent)
            {
                if (conx.Top >= cony.Top)
                    return 1;
                else if (conx.Top == cony.Top)
                {
                    if (conx.Left > cony.Left)
                        return 1;
                    else
                        return -1;
                }
            }
            else
            {
                if (conx.Top >= cony.Top)
                    return 1;
                else
                    return -1;
            }
            return 0;
        }
    }

       


   
}
